import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class dome3 {

    public static void main(String[] args) throws SQLException {
       // 1.创建dataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.连接数据库
        Connection connection = dataSource.getConnection();
        //3.构造sql
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,2);//前面‘1’表示sql语句中第几个？号，后面‘2’表示对应？的值
        //ResultSet 表示查询的结果集(临时表)   此处需要针对表遍历来获取数据
        //4.执行sql
        ResultSet resultSet = statement.executeQuery();
        //5.遍历结果集合
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = "+ id+"name = "+ name);
        }
        //6.释放
        resultSet.close();
        statement.close();
        connection.close();
    }
}
